'use strict';

const BaseModel = require('./BaseModel');

/**
 * 单位/部门 表信息
 */
class SysBranchModel extends BaseModel {

  constructor() {
    super('sys_branch', 'code');

    this.entity = class entity {
      constructor() {
        this.code = null;
        this.name = null;
        this.parentCode = null;
        this.type = null;
        this.areaId = null;
        this.remarks = null;
        this.creatorId = null;
        this.createTime = null;
        this.updateTime = null;
      }
    };
  }
  /*
   * 添加单位
   */
  async addBranch(app, models) {
    return await app.mysql.insert('sys_branch', models);
  }
  /*
   * 删除单位
   */
  async delBranch(app, code) {
    return await app.mysql.delete('sys_branch', {
      code,
    });
  }
  /*
   * 修改单位
   */
  async updateBranch(app, code, models) {
    return app.mysql.update('sys_branch', models, {
      where: {
        code,
      },
    });
  }
  /*
   * 查询所有单位
   */
  async findAllBranch(app) {
    const sql = 'select sys_branch.*,sys_area.name as area_name FROM sys_branch, sys_area where sys_branch.area_id = sys_area.code';
    return await app.mysql.query(sql);
  }
  /**
   *  查询所有叶子节点
   */
  async queryLeafBranch(app, request) {
      let sql = "select sys_branch.*,sys_area.name as area_name FROM sys_branch, sys_area where sys_branch.area_id = sys_area.code AND sys_branch.parent_code IS NOT NULL AND sys_branch.parent_code != ''";
      // 增加用户数据权限
      if (request.userRights && request.userRights.branchCodes) {
        sql += ` and sys_branch.code in (${request.userRights.branchCodes})`;
      }
      return await app.mysql.query(sql);
  }
  /*
   * 查询单位详情
   */
  async findBranchByCode(app, code) {
    const sql = `select * from sys_branch where code = '${code}' `;
    return await app.mysql.query(sql);
  }
  /*
   * 宠物注册表中有的区域代码，不能删除该区域
   */
  async findBranchByCodeOfPetRegister(app, code) {
    const sql = `select id from pet_register_info where area_code = '${code}' `;
    console.log(71, sql);
    return await app.mysql.query(sql);
  }
   
  async queryAllBranch(app) {
   const sql = ' select * from sys_branch';
   return await app.mysql.query(sql);
  }
}

module.exports = SysBranchModel;
